﻿using System.Text.RegularExpressions;
using StudyCompanion.Commons.Cache;
using StudyCompanion.Commons.Image;
using StudyCompanion.Commons.Result;
using StudyCompanion.Core.Aliyun;
using StudyCompanion.Core.Repository;
using StudyCompanion.Core.Services;
using StudyCompanion.Entity.User;
using StudyCompanion.IServices;

namespace StudyCompanion.Services;

public class SysService : BaseService, ISysService
{
    private readonly BaseRepository<Users> _useRepository;

    /// <summary>
    /// </summary>
    /// <param name="useRepository"></param>
    public SysService(BaseRepository<Users> useRepository)
    {
        _useRepository = useRepository;
    }

    /// <summary>
    ///     Id发送验证码
    /// </summary>
    /// <param name="uId"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public CommonResult IdSms(long uId)
    {
        var useInfo = _useRepository.Where(x => x.Id == uId).First();
        if (useInfo == null) return Problem("用户不存在");

        if (!RedisLock.Lock($"idSMSLock:{uId}"))
            return Problem("请勿频繁操作");
        if (string.IsNullOrEmpty(useInfo.Phone))
            return Problem("手机号必填");
        const string isTel = @"^1[3456789]\d{9}$"; //手机号正则校验
        if (!Regex.IsMatch(useInfo.Phone, isTel))
            return Problem("手机号格式错误");
        var code = new Random().Next(1000, 9999);
        var smsJson = "{\"code\":\"" + code + "\"}";
        RedisHelper.Set($"idSMS:{useInfo.Phone}", code, 60 * 10);
        var res = new Sms().SendSms(useInfo.Phone, smsJson);
        RedisLock.DelLock($"idSMSLock:{uId}");
        return res.Item1 ? Success() : Problem(res.Item2);
    }

    /// <summary>
    ///     图形验证码
    /// </summary>
    /// <param name="code"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public byte[] GetVerifyCode(string code, int width = 1000, int height = 40)
        => VerifyCode.GetVerifyCodeImage(code, width, height, 3);
}